package bots.neural;

import bots.AbstractBot;
import model.Field;
import model.Figure;
import model.GameType;
import model.Position;
import org.apache.log4j.Logger;
import org.encog.engine.network.activation.ActivationSigmoid;
import org.encog.ml.data.MLData;
import org.encog.ml.data.basic.BasicMLData;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
import util.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
* @author Alex Vikharev alex.vikharev@gmail.com
*         created 04.02.12
*/
public class SecondNNBot extends AbstractBot {

    private static final Logger log = Logger.getLogger(SecondNNBot.class);
    private final BasicNetwork network;
    private long randomMoves;
    private long totalMoves;

    public void resetStatistics() {
        randomMoves = 0;
        totalMoves = 0;
    }

    public BasicNetwork getNetwork() {
        return network;
    }

    public SecondNNBot(String name, GameType gameType, File file) throws IOException {
        super(name, gameType);
        network = new BasicNetwork();
        network.addLayer(new BasicLayer(17));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 17));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 17));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 1));
        network.getStructure().finalizeStructure();

        List<Double> list = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringTokenizer st = new StringTokenizer(reader.readLine());
        while (st.hasMoreTokens()) {
            list.add(Double.parseDouble(st.nextToken()));
        }
        double[] weights = new double[list.size()];
        for (int i = 0; i < list.size(); i++) {
            weights[i] = list.get(i);
        }
        network.decodeFromArray(weights);
        reader.close();
    }


    @Override
    public Position setFigure(Field field, Figure figure) {
        List<Figure> freeFigures = freeFigures(field, figure);
        Position bestMove = null;
        double bestResult = 0;
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                if (field.get(x, y) == null) {
                    if (freeFigures.isEmpty()) {
                        bestMove = new Position(field.addFigure(x, y, figure), null);
                    } else {
                        for (Figure freeFigure : freeFigures) {
                            Position move = new Position(field.addFigure(x, y, figure), freeFigure);
                            double v = computeNetwork(move);
                            if (v > bestResult) {
                                bestMove = move;
                                bestResult = v;
                            }
                        }
                    }
                }
            }
        }
        totalMoves++;
        if (bestMove != null) {
            return bestMove;
        } else {
            randomMoves++;
            return setRandomFigure(field, figure);
        }
    }

    public double getRandomMovesPercent() {
        return randomMoves * 1.0 / totalMoves;
    }

    private double computeNetwork(Position move) {
        MLData data = new BasicMLData(Util.BITWISE_CONVERTER.apply(Util.getCanonical(move)));
        MLData result = network.compute(data);
        return result.getData(0);
    }

}
